﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraExport;
using DevExpress.XtraGrid.Export;
using DevExpress.XtraTreeList;
using DevExpress.XtraBars;
using System.Text.RegularExpressions;
using Gem_Tools_Entity.Gem_Tools;
using DevExpress.XtraTreeList.Columns;

namespace GE_Management_Tool
{
    public class CCommon_Function
    {
        /// <summary>
        /// Show message dạng info
        /// </summary>
        /// <param name="p_strMessage"></param>
        public static void ShowMessage(string p_strMessage)
        {
            MessageBox.Show(p_strMessage, "Thông Tin", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// Show message dạng info
        /// </summary>
        /// <param name="p_strMessage"></param>
        public static DialogResult ShowQuestion(string p_strMessage)
        {
            return MessageBox.Show(p_strMessage, "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        }

        public static string ShowSaveFileDialog(string title, string filter)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            string name = Application.ProductName;
            int n = name.LastIndexOf(".") + 1;
            if (n > 0) name = name.Substring(n, name.Length - n);
            dlg.Title = "Export To " + title;
            dlg.FileName = name;
            dlg.Filter = filter;
            if (dlg.ShowDialog() == DialogResult.OK) return dlg.FileName;
            return "";
        }

        //public static void ExportTo(GridView p_grid, IExportProvider provider)
        //{
        //    Cursor currentCursor = Cursor.Current;
        //    Cursor.Current = Cursors.WaitCursor;

        //    BaseExportLink link = p_grid.CreateExportLink(provider);
        //    (link as GridViewExportLink).ExpandAll = false;
        //    link.ExportTo(true);
        //    provider.Dispose();
        //    Cursor.Current = currentCursor;
        //}

        /// <summary>
        /// Export 1 file ra excel
        /// </summary>
        /// <param name="p_grid"></param>
        /// <param name="p_strFile_Name"></param>
        public static void Export_To_Excel(GridView p_grid, string p_strFile_Name)
        {
            p_grid.OptionsPrint.PrintDetails = true;
            p_grid.OptionsPrint.ExpandAllDetails = true;
            p_grid.OptionsPrint.ExpandAllGroups = true;
            p_grid.ExportToXls(p_strFile_Name);
        }

        //public static void Export_Master_Grid_To(GridView p_grid, string p_strFile_Name)
        //{
        //    Cursor currentCursor = Cursor.Current;
        //    Cursor.Current = Cursors.WaitCursor;

        //    GridViewExportLink gvLink = p_grid.CreateExportLink(
        //      new ExportHtmlProvider(p_strFile_Name)) as GridViewExportLink;
        //    gvLink.ExportAll = true;
        //    gvLink.ExpandAll = true;
        //    gvLink.ExportTo(true);
        //    Cursor.Current = currentCursor;
        //}

        public static void OpenFile(string fileName)
        {
            if (XtraMessageBox.Show("Bạn có muốn mở file này lên xem không?", "Open file",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo.FileName = fileName;
                    process.StartInfo.Verb = "Open";
                    process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                    process.Start();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        public static Control Search_Control(Form p_frm, Control p_objCon, string p_strName)
        {
            Control v_objRes = null;

            if (p_objCon != null)
            {
                if (p_objCon.Name == p_strName)
                    v_objRes = p_objCon;
                else
                {
                    if (p_objCon.Controls != null)
                    {
                        foreach (Control v_con in p_objCon.Controls)
                        {
                            v_objRes = Search_Control(p_frm, v_con, p_strName);
                            if (v_objRes != null)
                                break;
                        }
                    } // end if
                } // end else
            } // end if
            else
            {
                foreach (Control v_con in p_frm.Controls)
                {
                    v_objRes = Search_Control(p_frm, v_con, p_strName);
                    if (v_objRes != null)
                        break;
                }
            }

            return v_objRes;
        }

        public static void Format_MenuBar(DevExpress.XtraBars.Bar p_objBar)
        {
            p_objBar.OptionsBar.AllowQuickCustomization = false;
            p_objBar.OptionsBar.DrawDragBorder = false;
            p_objBar.BarItemHorzIndent = 5;
        }

        public static void Format_ToolBar(DevExpress.XtraBars.Bar p_objBar)
        {
            p_objBar.OptionsBar.AllowQuickCustomization = false;
            p_objBar.OptionsBar.DrawDragBorder = false;
            p_objBar.OptionsBar.UseWholeRow = true;
            p_objBar.OptionsBar.MultiLine = true;
            p_objBar.BarItemHorzIndent = 10;
        }

        public static void Format_StatusBar(DevExpress.XtraBars.Bar p_objBar)
        {
            foreach (BarItem v_objItem in p_objBar.Manager.Items)
                if (v_objItem.GetType().ToString().Equals("DevExpress.XtraBars.BarStaticItem"))
                {
                    BarStaticItem v_obj = (BarStaticItem)v_objItem;
                    v_obj.LeftIndent = 10;
                }
        }

        public static void Format_TreeList(DevExpress.XtraTreeList.TreeList p_objTree)
        {
            p_objTree.OptionsBehavior.Editable = false;
            p_objTree.OptionsView.ShowIndicator = false;
            p_objTree.OptionsBehavior.EnableFiltering = true;
            p_objTree.OptionsFilter.FilterMode = FilterMode.Smart;
            p_objTree.Appearance.HeaderPanel.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            p_objTree.Appearance.HeaderPanel.Options.UseTextOptions = true;
            p_objTree.OptionsSelection.EnableAppearanceFocusedCell = false;

            foreach (TreeListColumn v_objColumn in p_objTree.Columns)
            {
                v_objColumn.OptionsFilter.AllowAutoFilter = true;
                v_objColumn.OptionsFilter.AllowFilter = true;
                v_objColumn.OptionsFilter.AutoFilterCondition = AutoFilterCondition.Contains;
            }
        }

        public static void Format_LookupEdit(DevExpress.XtraEditors.LookUpEdit p_objLookup)
        {
            p_objLookup.Properties.NullText = "";
            p_objLookup.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
        }

        public static void Format_DateTimeEdit(DevExpress.XtraEditors.DateEdit p_dtmDate)
        {
            p_dtmDate.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            p_dtmDate.Properties.DisplayFormat.FormatString = "dd-MMM-yyyy";
            p_dtmDate.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            p_dtmDate.Properties.EditFormat.FormatString = "dd-MMM-yyyy";
            p_dtmDate.Properties.EditMask = "dd-MMM-yyyy";
        }

        public static void Format_GridView(DevExpress.XtraGrid.Views.Grid.GridView p_objGrid)
        {
            p_objGrid.OptionsBehavior.Editable = false;
            p_objGrid.OptionsSelection.EnableAppearanceFocusedCell = false;
            p_objGrid.OptionsSelection.EnableAppearanceHideSelection = false;
            p_objGrid.OptionsView.ShowFooter = true;
            p_objGrid.OptionsView.ShowGroupedColumns = true;
            //p_objGrid.GroupPanelText = "Kéo và thả cột vào đây để phân loại dữ liệu";
            p_objGrid.Appearance.HeaderPanel.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            p_objGrid.Appearance.HeaderPanel.Options.UseTextOptions = true;
            p_objGrid.FocusRectStyle = DrawFocusRectStyle.RowFocus;
            p_objGrid.OptionsView.RowAutoHeight = true;
            p_objGrid.OptionsBehavior.AutoExpandAllGroups = true;
            p_objGrid.OptionsView.ShowAutoFilterRow = true;

            for (int v_i = 0; v_i < p_objGrid.Columns.Count; v_i++)
                p_objGrid.Columns[v_i].OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
        }

        public static void Format_GridView(DevExpress.XtraGrid.Views.Layout.LayoutView p_objGrid)
        {
            p_objGrid.OptionsBehavior.Editable = false;
            //p_objGrid.GroupPanelText = "Kéo và thả cột vào đây để phân loại dữ liệu";
            p_objGrid.Appearance.HeaderPanel.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            p_objGrid.Appearance.HeaderPanel.Options.UseTextOptions = true;

            for (int v_i = 0; v_i < p_objGrid.Columns.Count; v_i++)
                p_objGrid.Columns[v_i].OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
        }

        public static void Format_GridControl(DevExpress.XtraGrid.GridControl p_objGrid)
        {
            for (int v_i = 0; v_i < p_objGrid.Views.Count; v_i++)
            {
                if (p_objGrid.Views[v_i].GetType().ToString() == "DevExpress.XtraGrid.Views.Grid.GridView")
                {
                    Format_GridView((DevExpress.XtraGrid.Views.Grid.GridView)p_objGrid.Views[v_i]);
                }
                if (p_objGrid.Views[v_i].GetType().ToString() == "DevExpress.XtraGrid.Views.Layout.LayoutView")
                {
                    Format_GridView((DevExpress.XtraGrid.Views.Layout.LayoutView)p_objGrid.Views[v_i]);
                }
            }
        }

        /// <summary>
        /// Format BarManager
        /// </summary>
        /// <param name="p_objControl"></param>
        public static void Format_Bar(BarManager p_objBarManager)
        {
            foreach (DevExpress.XtraBars.Bar v_objBar in p_objBarManager.Bars)
            {
                // Menu bar
                if (v_objBar.IsMainMenu)
                    Format_MenuBar(v_objBar);

                // Status bar
                if (v_objBar.IsStatusBar)
                    Format_StatusBar(v_objBar);

                // Toolbar
                if (!v_objBar.IsMainMenu && !v_objBar.IsStatusBar)
                    Format_ToolBar(v_objBar);
            }
        }

        /// <summary>
        /// Format tất cả giao diện control trên của form cho đúng chuẩn
        /// </summary>
        /// <param name="p_frmForm"></param>
        public static void Format_All(Form p_frmForm)
        {
            foreach (Control v_objControl in p_frmForm.Controls)
                Format_Control(v_objControl);
        }

        /// <summary>
        /// Format tất cả giao diện control trên của form cho đúng chuẩn
        /// </summary>
        /// <param name="p_frmForm"></param>
        public static void Format_All(UserControl p_frmUc)
        {
            foreach (Control v_objControl in p_frmUc.Controls)
                Format_Control(v_objControl);
        }

        /// <summary>
        /// Format tất cả các giao diện control con của control cha cho đúng chuẩn
        /// </summary>
        /// <param name="p_objControl"></param>
        public static void Format_Control(Control p_objControl)
        {
            if (p_objControl.GetType().ToString() == "DevExpress.XtraGrid.GridControl")
                Format_GridControl((DevExpress.XtraGrid.GridControl)p_objControl);

            if (p_objControl.GetType().ToString() == "DevExpress.XtraEditors.LookUpEdit")
                Format_LookupEdit((DevExpress.XtraEditors.LookUpEdit)p_objControl);

            if (p_objControl.GetType().ToString() == "DevExpress.XtraEditors.DateEdit")
                Format_DateTimeEdit((DevExpress.XtraEditors.DateEdit)p_objControl);

            if (p_objControl.GetType().ToString() == "DevExpress.XtraTreeList.TreeList")
                Format_TreeList((DevExpress.XtraTreeList.TreeList)p_objControl);

            if (p_objControl.GetType().ToString() == "DevExpress.XtraScheduler.UI.ResourcesTree")
                Format_TreeList((DevExpress.XtraScheduler.UI.ResourcesTree)p_objControl);

            foreach (Control v_objControl in p_objControl.Controls)
                Format_Control(v_objControl);
        }

        /// <summary>
        /// Hàm chuyển các chuỗi có format "chuỗi cần chuyển" sang format "Chuỗi Cần Chuyển"
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Remove_Error_String(string str, int p_icheck) // check = 1 thì không kiểm tra trường hợp trong chuỗi có chữ Hoa.
        {
            str = str.Trim();
            char[] VietnameseSigns = new char[] {
            'a','A','à','À','á','Á','ạ','Ạ','ả','Ả','ã','Ã','â','Â','ấ','Ấ','ầ','Ầ','ậ','Ậ','ẩ','Ẩ',
            'ẫ','Ẫ','ă','Ă','ắ','Ắ','ằ','Ằ','ặ','Ặ','ẳ','Ẳ','ẵ','Ẵ',
            'b','B','c','C','d','D','đ','Đ',
            'e','E','é','É','è','È','ẹ','Ẹ','ẻ','Ẻ','ẽ','Ẽ','ê','Ê','ế','Ế','ề','Ề',
            'ệ','Ệ','ể','Ể','ễ','Ễ',
            'f','F','g','G','h','H',
            'i','I','í','Í','ì','Ì','ị','Ị','ỉ','Ỉ','ĩ','Ĩ',
            'j','J','k','K','l','L','m','M','n','N',
            'o','O','ò','Ò','ọ','Ọ','ỏ','Ỏ','õ','Õ','ô','Ô','ố','Ố','ồ','Ồ','ộ','Ộ','ổ','Ổ',
            'ỗ','Ỗ','ơ','Ơ','ớ','Ớ','ờ','Ờ','ợ','Ợ','ở','Ở','ỡ','Ỡ',
            'p','P','q','Q','r','R','s','S','t','T',
            'u','U','ú','Ú','ù','Ù','ụ','Ụ','ủ','Ủ','ũ','Ũ','ư','Ư','ứ','Ứ','ừ','Ừ','ự','Ự','ử','Ử','ữ','Ữ',
            'v','V','x','X',
            'y','Y','ý','Ý','ỳ','Ỳ','ỵ','Ỵ','ỷ','Ỷ','ỹ','Ỹ',
            'w','W','z','Z'};

            for (int v_i = 0; v_i < str.Length; v_i++)
            {
                for (int v_j = 0; v_j < VietnameseSigns.Length; v_j++)
                {
                    if (v_j % 2 == 0)
                    {
                        if (str[0] == VietnameseSigns[v_j])
                        {
                            str = VietnameseSigns[v_j + 1] + str.Substring(1, str.Length - 1);
                        }
                        if ((str[v_i] == ' ') && (str[v_i + 1] == VietnameseSigns[v_j]))
                        {
                            str = str.Substring(0, v_i + 1) + VietnameseSigns[v_j + 1] + str.Substring(v_i + 2, str.Length - v_i - 2);
                        }
                        if ((str[v_i] == '(') && (str[v_i + 1] == VietnameseSigns[v_j]))
                        {
                            str = str.Substring(0, v_i + 1) + VietnameseSigns[v_j + 1] + str.Substring(v_i + 2, str.Length - v_i - 2);
                        }
                        if ((str[v_i] == '_') && (str[v_i + 1] == VietnameseSigns[v_j]))
                        {
                            str = str.Substring(0, v_i + 1) + VietnameseSigns[v_j + 1] + str.Substring(v_i + 2, str.Length - v_i - 2);
                        }
                    }
                    else
                    {
                        if (v_i != 0 && str[v_i - 1] != ' ' && p_icheck != 1)
                        {
                            if (str[v_i] == VietnameseSigns[v_j])
                            {
                                str = str.Substring(0, v_i) + VietnameseSigns[v_j - 1] + str.Substring(v_i + 1, str.Length - v_i - 1);
                            }
                        }
                    }

                }
            }

            StringBuilder v_sbKq = new StringBuilder();
            str = str.Trim();
            for (int i = 0; i < str.Length; i++)
            {
                v_sbKq.Append(str[i]);
                if (str[i] == ' ')
                {
                    while (str[i] == ' ')
                    {
                        i++;
                    }
                    v_sbKq.Append(str[i]);
                }
            }

            return str;
        }

        /// <summary>
        /// Hàm convert các string có định dạng unicode sang TCVN3
        /// </summary>
        /// <param name="p_str">chuỗi cần chuyển</param>
        /// <returns></returns>
        public static string Convert_Unicode_To_TCVN3(string p_str)
        {
            char[] tcvnchars = {'µ','µ', '¸','¸', '¶','¶', '·','·', '¹', '¹',
                                '¨', '»', '»', '¾', '¾', '¼', '¼', '½', '½', 'Æ', 'Æ', 
                                '©', 'Ç', 'Ç', 'Ê', 'Ê', 'È', 'È', 'É', 'É', 'Ë', 'Ë', 
                                '®', 'Ì', 'Ì', 'Ð', 'Ð', 'Î', 'Î', 'Ï', 'Ï', 'Ñ', 'Ñ', 
                                'ª', 'Ò', 'Ò', 'Õ', 'Õ', 'Ó', 'Ó', 'Ô', 'Ô', 'Ö', 'Ö', 
                                '×', 'Ý', 'Ø', 'Ü', 'Þ', '×', 'Ý', 'Ø', 'Ü', 'Þ', 
                                'ß', 'ã', 'á', 'â', 'ä', 'ß', 'ã', 'á', 'â', 'ä', 

                                '«', 'å', 'è', 'æ', 'ç', 'é', 'å', 'è', 'æ', 'ç', 'é',  
                                '¬', 'ê', 'í', 'ë', 'ì', 'î', 'ê', 'í', 'ë', 'ì', 'î', 
                                'ï', 'ó', 'ñ', 'ò', 'ô', 'ï', 'ó', 'ñ', 'ò', 'ô', 
                                '­', 'õ', 'ø', 'ö', '÷', 'ù', 'õ', 'ø', 'ö', '÷', 'ù', 
                                'ú', 'ý', 'û', 'ü', 'þ','ú', 'ý', 'û', 'ü', 'þ', 
                                '¡', '¢', '§', '£', '¤', '¥', '¦'};

            char[] unichars = { 'À', 'à', 'Á', 'á', 'Ả', 'ả', 'Ã', 'ã', 'Ạ', 'ạ', 
                                'ă', 'Ằ', 'ằ', 'Ắ', 'ắ', 'Ẳ', 'ẳ', 'Ẵ', 'ẵ', 'Ặ', 'ặ', 
                                'â', 'Ầ', 'ầ', 'Ấ', 'ấ', 'Ẩ', 'ẩ', 'Ẫ', 'ẫ', 'Ậ', 'ậ', 
                                'đ', 'È', 'è', 'É', 'é', 'Ẻ', 'ẻ', 'Ẽ', 'ẽ', 'Ẹ', 'ẹ', 
                                'ê', 'Ề', 'ề', 'Ế', 'ế', 'Ể', 'ể', 'Ễ', 'ễ', 'Ệ', 'ệ', 
                                'ì', 'í', 'ỉ', 'ĩ', 'ị', 'Ì', 'Í', 'Ỉ', 'Ĩ', 'Ị', 
                                'ò', 'ó', 'ỏ', 'õ', 'ọ', 'Ò', 'Ó', 'Ỏ', 'Õ', 'Ọ',

                                'ô', 'ồ', 'ố', 'ổ', 'ỗ', 'ộ', 'Ồ', 'Ố', 'Ổ', 'Ỗ', 'Ộ',  
                                'ơ', 'ờ', 'ớ', 'ở', 'ỡ', 'ợ', 'Ờ', 'Ớ', 'Ở', 'Ỡ', 'Ợ',
                                'ù', 'ú', 'ủ', 'ũ', 'ụ', 'Ù', 'Ú', 'Ủ', 'Ũ', 'Ụ', 
                                'ư', 'ừ', 'ứ', 'ử', 'ữ', 'ự', 'Ừ', 'Ứ', 'Ử', 'Ữ', 'Ự', 
                                'ỳ', 'ý', 'ỷ', 'ỹ', 'ỵ', 'Ỳ', 'Ý', 'Ỷ', 'Ỹ', 'Ỵ', 
                                'Ă', 'Â', 'Đ', 'Ê', 'Ô', 'Ơ', 'Ư'};


            char[] v_tmp = p_str.ToCharArray();
            IDictionary<char, char> v_dic = new Dictionary<char, char>();
            for (int v_i = 0; v_i < unichars.Length; v_i++)
            {
                v_dic.Add(unichars[v_i], tcvnchars[v_i]);
            }
            char v_k = new char();
            for (int v_j = 0; v_j < v_tmp.Length; v_j++)
            {
                if (v_dic.ContainsKey(v_tmp[v_j]))
                {
                    v_dic.TryGetValue(v_tmp[v_j], out v_k);
                    v_tmp[v_j] = v_k;
                }
            }


            return new string(v_tmp);
        }

        public static string Loai_Bo_Dau_TV(string accented)
        {
            Regex regex = new Regex(@"\p{IsCombiningDiacriticalMarks}+");
            string strFormD = accented.Normalize(System.Text.NormalizationForm.FormD);
            return regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
        }

        public class CloneableList<T> : List<T>, ICloneable where T : ICloneable
        {
            public object Clone()
            {
                var clone = new List<T>();
                ForEach(item => clone.Add((T)item.Clone()));
                return clone;
            }
        }

        public void Check_Role(Form p_frmForm, ref Boolean Allow_Add, ref Boolean Allow_Update, ref Boolean Allow_Delete)
        {



            //if (p_frmRole.Is_Show <= 0)
            //{
            //    p_frmForm.Close();
            //    throw new Exception("Access Denied.");
            //}
            //if (p_frmRole.Is_Add <= 0)
            //{
            //    Allow_Add = false;
            //}
            //if (p_frmRole.Is_Update <= 0)
            //{
            //    Allow_Update = false;
            //}
            //if (p_frmRole.Is_Delete <= 0)
            //{
            //    Allow_Delete = false;
            //}
        }
    }
}
